package jobflow.dao;

import java.util.List;

import javax.faces.component.html.HtmlInputSecret;

import javax.faces.context.FacesContext;
import javax.persistence.EntityManager;
import jobflow.entity.Kullanici;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.richfaces.component.html.HtmlInputText;

@Name("authenticator")
@Scope(ScopeType.SESSION)
public class Authenticator

{

	FacesContext context = FacesContext.getCurrentInstance();

	@In
	Identity identity;
	@In
	Credentials credentials;

	@In
	EntityManager entityManager;

	@SuppressWarnings("unused")
	@In(required = false)
	private Kullanici kullanici;

	HtmlInputText userName = null;
	HtmlInputSecret passWord=null;

	public boolean authenticate() {
		
		
		 userName = (HtmlInputText) context.getViewRoot()
		.findComponent("loginForm:username");
           passWord = (HtmlInputSecret) context.getViewRoot()
		.findComponent("loginForm:password");

		List<Kullanici> kullaniciList = entityManager
		     .createQuery("select k from Kullanici k where k.sifre=#{identity.password} and k.kullaniciAdi=#{identity.username}").getResultList();
				

		if (kullaniciList.size() != 0) {
			kullanici = kullaniciList.get(0);

			deletePassWordAndUserName();
			return true;
		} else {
			deletePassWordAndUserName();
			return false;
		}

	}

	private void deletePassWordAndUserName() {
		
		userName.setValue(null);
		passWord.setValue(null);

	}
	
	

}
